//csp filter util methods
Array.prototype.indexOf = function(val) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == val) return i;
    }
    return -1;
};
Array.prototype.remove = function(val) {
    var index = this.indexOf(val);
    if (index > -1) {
        this.splice(index, 1);
    }
}; 
//global parameters
var initFlag = false; 
var realCert ; 
//initMethod 初始化浏览器控件 
function initTopesa () {
	if(initFlag){
		return 0;
	}else{
		var config = {
			"license":"MIIG5AYJKoZIhvcNAQcCoIIG1TCCBtECAQExDjAMBggqgRzPVQGDEQUAMIICKQYJKoZIhvcNAQcBoIICGgSCAhZ7Iklzc3VlciI6IigoKC4qQ049aVRydXNDaGluYSBSU0EgVGVzdCBVc2VyIENBLiopfCguKk9VPVRlc3QuKil8KC4qTz1pVHJ1c0NoaW5hLiopfCguKkM9Q04uKikpezR9fCgoLipDTj1pVHJ1c0NoaW5hIFNNMiBUZXN0IFVzZXIgQ0EuKil8KC4qT1U9VGVzdC4qKXwoLipPPWlUcnVzQ2hpbmEuKil8KC4qQz1DTi4qKSl7NH18KCguKkNOPWlUcnVzQ2hpbmEgRW50ZXJwcmlzZSBVc2VyIENBIC0gUlNBLiopfCguKk9VPUVudGVycHJpc2UuKil8KC4qTz1pVHJ1c0NoaW5hLiopfCguKkM9Q04uKikpezR9fCgoLipDTj1pVHJ1c0NoaW5hIEVudGVycHJpc2UgVXNlciBDQSAtIFNNMi4qKXwoLipPVT1FbnRlcnByaXNlLiopfCguKk89aVRydXNDaGluYS4qKXwoLipDPUNOLiopKXs0fXwoKC4qTz3lpKnlqIHor5rkv6HmtYvor5Xns7vnu58uKikpezF9KSIsInZlcnNpb24iOiIxLjAuMC4xIiwic29mdFZlcnNpb24iOiIzLjEuMC4wIiwibm90YWZ0ZXIiOiIyMDI4LTExLTA3Iiwibm90YmVmb3JlIjoiMjAxOC0xMS0wNyIsIm5vQWxlcnQiOiJ0cnVlIn2gggNEMIIDQDCCAuWgAwIBAgIUXyWc2syCu37zBbMAe4uOyb35tfIwDAYIKoEcz1UBg3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sxggFFMIIBQQIBATBtMFUxJjAkBgNVBAMMHeWkqeivmuWuieS/oea1i+ivlVNNMueUqOaIt0NBMQ4wDAYDVQQLDAVUT1BDQTEOMAwGA1UECgwFVE9QQ0ExCzAJBgNVBAYTAkNOAhRfJZzazIK7fvMFswB7i47Jvfm18jAMBggqgRzPVQGDEQUAoGkwGAYJKoZIhvcNAQkDMQsGCSqGSIb3DQEHATAcBgkqhkiG9w0BCQUxDxcNMTUwNTAxMTQwNDU4WjAvBgkqhkiG9w0BCQQxIgQgXW9V6Mry3iSO+nGFVSIWZvZlfAyouiIepXB2SWuopFEwDAYIKoEcz1UBgi0FAARGMEQCILtmCFpdK6+QOhq00XvbqaSDbSdnfn0xbKXVYd+Wn24uAiD0soWoLCWqGAdlvZwW8NJH1UX7TNtYy1Mk1AK2DJvGkA==",
			"certDateFmtMode":true,
			//"disableExeUrl":true,
			"exepath" : "http://127.0.0.1/portal/download/TopCertKit-3.1.0.102.6.exe"
		};
		try{
			TCA.config(config);
			initFlag = true;
			return 0;
		}catch(e){
			if (e instanceof TCACErr) {
		      alert("未能加载客户端组件，请下载安装控件! 安装完成请刷新网页!");
		    } else {
		      alert("未能加载客户端组件，请下载安装控件! 安装完成请刷新网页!");
		    }
			downloadTopEsa();
		}
	}	
  
}

//下载控件
function downloadTopEsa(){
	try{ 
		var elemIF = document.createElement("iframe");   
		elemIF.src = "http://127.0.0.1/portal/download/TopCertKit-3.1.0.102.6.exe";   
		elemIF.style.display = "none";   
		document.body.appendChild(elemIF);   
	}catch(e){ 
		alert("控件下载异常！");
	}
 }
//get cert by ncid 根据传入的NC登录名，查找证书，如找到证书，返回证书；如未找到证书，抛出错误 1-5
function getcert(ncid){
	if(typeof(realCert)!="undefined"&&realCert!=null){
		return realCert;
	}
	var flag = initTopesa();
	if(flag!=0){
		throw new Error(5,"控件初始化失败");
	}
	var certs = CertStore.listAllCerts();
	certs = certs.forSign();
	var count = certs.size();
	if(certs.size()==0){
		throw new Error(3,"无符合证书");
	}
	
	var hasKeyCert = false;
	var csps = CertStore.listStore();
	csps.remove("Microsoft Enhanced Cryptographic Provider v1.0");
	csps.remove("Microsoft Base Cryptographic Provider v1.0");
	csps.remove("Microsoft Base Smart Card Crypto Provider");
	csps.remove("Microsoft Strong Cryptographic Provider");
	if(csps.length<1){
		throw new Error(4,"Ukey驱动未安装");
	}
	for(var i = 0;i<csps.length;i++){
		if(CertStore.byName(csps[i]).listCerts().size()>0){
			hasKeyCert = true;
			break;
		}
	}
	if(!hasKeyCert){
		throw new Error(1,"Ukey未插入");
	}
	
	for (var i = 0; i<count; i++) {
		var cert = certs.get(i);
		var subject = cert.subject();
		var userid=getcertUID(subject);
		if(typeof(userid)=="undefined"||userid==""){
			continue;				
		}
		if(userid==ncid){
			realCert = cert;
			return realCert;
		}	
	}	
	throw new Error(2,"登陆用户与Ukey不匹配");
}
//check ncid [*]判断登录名与证书中截取的'UID'一致 
function getNCID(ncid){
	var cert = getcert(ncid);
	return getcertUID(cert.subject());
}
//split certSubject to get 'UID' 拆分证书的主题项以获取'UID'
function getcertUID(subject){
	var str = new Array();
	str = subject.split(",");
	for(var j=0;j<str.length;j++)
	{
		var str2=str[j].split("=");
		for(var k=0;k<str2.length;k++)
		{
			var str3=str2[k].split(":");
			if(str3[0]=='UID')
			{   
				if( str3[1].charCodeAt(str3[1].length-1)==0 )
					return str3[1].substr(0, str3[1].length-1);
				return str3[1];
			}
		}
	}
	return;
}

//get cert serialnumber [*1] 根据登录名，获取证书序列号 
function getSN(ncid){
	try {
		var cert = getcert(ncid);
		return cert.serialNumber();		
	}catch (e) {
		if (e instanceof TCACErr) {
			e.name = e.message;
			throw e;
		} else {
			if (e.number == 1 || e.number ==2 || e.number ==3 || e.number ==4 || e.number ==5){
				e.name = e.message;
			} 
			throw e;
		}
	}
}	
//check password [*2] 校验UKEY的密码，验证成功返回0，不成功返回其他值
function CheckPassword(pwd,cert){
    if(cert instanceof Certificate){
	}else{
		cert = getcert(cert);
		if(cert ==62||cert ==63){
			return cert;
		}
	}
	
	try{
		return SetUKeyPINWithCert(cert,pwd);
	}catch(e){
		if (e instanceof TCACErr) {
      		return 62;
    	} else {
      		return 63;
    	}
	}
	return 32;
}
//sign message [*3]消息签名
function signmessage(message,cert){
	if(cert instanceof Certificate){
	}else{
		cert = getcert(cert);
		if(cert ==62||cert ==63){
			return 1;
		}
	}
	try{
		if(message==null||message==""||typeof(message) == "undefined"){    
			return 2;
		}
		var sigmsg = cert.signMessageRaw(message);
		return sigmsg;
	}catch(e){
		if (e instanceof TCACErr) {
      		return 62;
    	} else {
      		return 63;
    	}
	}
}

function verfiymessage(message,signature,cert){
	try{
		if(cert==null){    
			return;
		}
		if(message==null||message==""){    
			return;
		}
		if(signature==null||signature==""){    
			return;
		}
		var ret = null;	
		ret = cert.verifyRaw(signature,message);
		return ret;
	}catch(e){
		if (e instanceof TCACErr) {
			return 62;
		} else {
			return 63;
		}
	}
}

function SetUKeyPINWithCert(cert,certPin){
	try{
		var password = certPin;
		var TcapUkey = cert.getUKeyPINVerifyer();
		if(password!=null){
			var result = TcapUkey.SetUKeyPINWithCSP(password);
			return result;
		}
	}catch(e){
		if (e instanceof TCACErr) {
      		return 62;
    	} else {
      		return 63;
    	}
	}
}
function VerPIN(){
  var cert = getSelectedCert();
  var TcapUkey = cert.getUKeyPINVerifyer();
	try{
		TcapUkey.VerPIN();
	}catch(e){
		if (e instanceof TCACErr) {
    	} else {
    	}
	}
}
function getcertBase64(cert){
	try {
		return cert.b64str();		
	}catch (e) {
		if (e instanceof TCACErr) {
			return 62;
		} else {
			return 63;
		}
	}
}
//signFile2Message ebvp
function SignFile(fileName, cert){
	if(cert instanceof Certificate){
	}else{
		cert = getcert(cert);
		if(cert ==62||cert ==63){
			return cert;
		}
	}
	var filehash = HashUtil.hashFile(fileName, TCA.SHA1);
	var signature= cert.signMessageRaw(filehash);
	return signature;	
}
//verifyFileWhithMessage ebvp
function verfiyFile(fileName,signature,certBase64){
	var cert = parseCertBase64ToCert(certBase64);
	var filehash = HashUtil.hashFile(fileName, TCA.SHA1);
	try{
		if(cert==null){    
			return;
		}
		if(filehash==null||filehash==""){    
			return;
		}
		if(signature==null||signature==""){    
			return;
		}
		var ret = cert.verifyRaw(signature,filehash);
		if(ret==0){
			return true;
		}else{
			return false;
		}
	}catch(e){
		if (e instanceof TCACErr) {
			return false;
		} else {
			return false;
		}
	}
}
function parseCertBase64ToCert(certBase64){
	return new Certificate(b64str);
}

